/*
 * SerialCommunication.cpp
 *
 * @author Bematech S.A.
 */

#include "bilbao/protocol/serial/SerialCommunication.h"

namespace bilbao
{
	namespace protocol
	{
		namespace serial
		{
			//--------------------------------------------------------------------------------
			SerialCommunication* SerialCommunication::_instance = NULL;
			SerialCommunicationManager* SerialCommunication::_manager = NULL;
			//--------------------------------------------------------------------------------
			SerialCommunication::SerialCommunication( void ) :
				_serialPort( 0 ), _read(), _write(), _filaComandos(), _filaRespostas()
			{
				//Do nothing
			}
			//--------------------------------------------------------------------------------
			SerialCommunication::SerialCommunication( util::SerialPort* serialPort ) :
				_serialPort( serialPort ), _filaComandos(), _filaRespostas(),
				_read( _serialPort, &_filaComandos ), _write( &_filaRespostas, _serialPort )
			{
				_read.start();
				_write.start();
			}
			//--------------------------------------------------------------------------------
			SerialCommunication::~SerialCommunication( void )
			{
				delete _manager;
				_manager = 0;

				delete _instance;
				_instance = 0;
			}
			//--------------------------------------------------------------------------------
			SerialCommunication* SerialCommunication::getInstance( util::SerialPort* sp )
			{
				_manager = SerialCommunicationManager::getInstance();

				return _manager->demandSerialCommunication( sp );
			}
			//--------------------------------------------------------------------------------
			void SerialCommunication::read( Vector<String>& buffMessages )
			{
				if ( _filaComandos.empty() )
					return; // return false;

				String str = "";
				_filaComandos.pop( str );
				util::Tokenizer tk( str );
				buffMessages = tk.split();

				led::LedController* led = led::LedController::getInstance();
				led->turnOff( L_CEL );
				// return !buffMessages.empty();
			}
			//--------------------------------------------------------------------------------
			void SerialCommunication::send( const String& buffer )
			{
				_filaRespostas.push( buffer );
			}
			//--------------------------------------------------------------------------------
		}
	}
}
